<template>
  <div class="dashboard-container">
    <h1 style="text-align: center">订房管理</h1>
    <!-- 查询条件区域 -->
    <div style="margin-top: 0; display: flex; align-items: center;">
      <!-- 新增按钮 -->
      <el-button plain style="width:80px;margin-top:0;margin-left:20%;background-color: pink; border-radius: 8px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);" @click="addButton">
        新增
      </el-button>
      <el-select v-model="state" clearable placeholder="预定状态" style="margin-left: 40px;width: 200px">
        <el-option v-for="item in stateOptions" :key="item.state" :label="item.state" :value="item.state"/>
      </el-select>
      <el-input v-model="roomNumber" placeholder="房间号" name="roomNumber" type="text" clearable style="margin-left:40px ;width: 180px"/>
      <el-input v-model="reserveId" placeholder="预定ID" name="roomNumber" type="text" clearable style="margin-left:40px ;width: 180px"/>
      <el-button plain style="width:80px;margin-top:0;margin-left:40px ;background-color: pink; border-radius: 8px; " @click="selectAll">
        查询
      </el-button>
      <el-button style="width:80px;margin-top:0;margin-left:40px ;background-color: white; border-radius: 8px;" @click="checkReserve">
        重置</el-button>
    </div>
    <!-- 订房记录表格 -->
    <el-table :data="reserveList" height="659px" border style="width: 100%;margin-top: 20px" class="elegant-room-table">
      <el-table-column align="center" fixed prop="reserveId" label="预定ID" min-width="100"/>
      <el-table-column align="center" fixed prop="roomNumber" label="房间号" min-width="100"/>
      <el-table-column align="center" fixed prop="customerName" label="顾客名称" width="100"/>
      <el-table-column align="center" fixed prop="identificationCard" label="身份证号" width="165"/>
      <el-table-column align="center" fixed prop="state" label="房间状态" min-width="130">
        <template v-slot="scope">
          <span :class="{
              'state-green': ['空闲', '预定中'].includes(scope.row.state),
              'state-red': scope.row.state === '已入住'
            }">
            {{ scope.row.state }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed prop="liveId" label="订单ID" min-width="100"/>
      <el-table-column align="center" fixed prop="reserveTime" label="预定时间" min-width="120"/>
      <el-table-column align="center" fixed prop="reserveLiveTime" label="入住时间" width="120"/>
      <el-table-column align="center" fixed prop="reserveDayNumber" label="入住天数" width="100"/>
      <el-table-column align="center" fixed prop="remark" label="备注" width="130"/>
      <el-table-column align="center" fixed prop="abrogateIdentity" label="作废标识" width="110"/>
      <el-table-column align="center" fixed label="操作" width="150">
        <template v-slot="scope">
          <el-button
            type="text"
            v-if="scope.row.state === '预定中'"
            @click="updateButton(scope.row)"
          >入住</el-button>
          <el-button
            type="text"
            v-if="scope.row.state === '预定中'"
            @click="cancelReserveButton(scope.row)"
          >取消</el-button>
          <el-button
            type="text"
            v-if="scope.row.state === '预定中'"
            @click="abrogateReserveButton(scope.row)"
          >作废</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增对话框 -->
    <el-dialog
      title="新增"
      :visible.sync="addButtonController"
      width="50%"
      @close="closeReserve('ruleForm')"
    >
      <el-form
        label-width="20%"
        :model="addList"
        :rules="Reserves"
        ref="ruleForm"
      >
        <el-form-item label="房间" prop="roomId">
          <el-select
            v-model="addList.roomId"
            clearable
            placeholder="房间"
            class="full-width"
          >
            <el-option
              v-for="item in roomOptions"
              :key="item.roomId"
              :label="item.roomNumber"
              :value="item.roomId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="顾客" prop="customerId">
          <el-select
            v-model="addList.customerId"
            clearable
            placeholder="顾客"
            class="full-width"
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.customerId"
              :label="item.customerName + '-' + item.identificationCard"
              :value="item.customerId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="入住时间" prop="reserveLiveTime">
          <el-date-picker
            v-model="addList.reserveLiveTime"
            type="date"
            placeholder="请选择入住日期"
            value-format="yyyy-MM-dd"
            class="full-width"
            clearable
          />
        </el-form-item>

        <el-form-item label="入住天数" prop="reserveDayNumber">
          <el-input
            v-model="addList.reserveDayNumber"
            show-word-limit
            class="full-width"
            clearable
            placeholder="请输入您要入住的天数"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="addList.remark"
            show-word-limit
            class="full-width"
            clearable
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addReserve('ruleForm')">确 定</el-button>
        <el-button @click="closeReserve('ruleForm')">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 入住对话框 -->
    <el-dialog
      title="入住"
      :visible.sync="updateButtonController"
      width="30%"
      @close="closeDialog('updateButtonController')"
    >
      <el-form label-width="20%" ref="updateForm">
        <p style="text-align: center; font-size: 16px;">确认是否入住</p>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" plain @click="updateAllReserve">确 定</el-button>
        <el-button plain @click="closeDialog('updateButtonController')">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 取消对话框 -->
    <el-dialog
      title="取消"
      :visible.sync="cancelReserveController"
      width="30%"
      @close="closeDialog('cancelReserveController')"
    >
      <el-form label-width="20%" ref="cancelForm">
        <p style="text-align: center; font-size: 16px;">确认是否取消</p>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" plain @click="cancelAllReserve">确 定</el-button>
        <el-button plain @click="closeDialog('cancelReserveController')">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 作废对话框 -->
    <el-dialog
      title="作废"
      :visible.sync="abrogateReserveController"
      width="30%"
      @close="closeDialog('abrogateReserveController')"
    >
      <el-form label-width="20%" ref="abrogateForm">
        <p style="text-align: center; font-size: 16px;">确认是否作废</p>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" plain @click="abrogateAllReserve">确 定</el-button>
        <el-button plain @click="closeDialog('abrogateReserveController')">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { selectAllCustomer } from '@/api/Customer'
import { abrogateReserve1, cancelReserve1, insertReserve, selectAllReserve, updateReserve1 } from '@/api/reserve'
import { selectAllRoom } from '@/api/room'

export default {
  name: 'ReserveManagement',
  computed: {
    ...mapGetters([
      'userId',
      'userName',
      'roleName'
    ])
  },
  data() {
    return {
      // 查询条件
      state: '',
      roomNumber: '',
      reserveId: '',

      // 数据列表
      reserveList: [],

      // 对话框控制
      addButtonController: false,
      updateButtonController: false,
      cancelReserveController: false,
      abrogateReserveController: false,

      // 下拉选项数据
      roomOptions: [],
      customerOptions: [],
      stateOptions: [],

      // 新增表单数据
      addList: {
        customerId: '',
        roomId: '',
        roomNumber: '',
        customerName: '',
        reserveLiveTime: '',
        identificationCard: '',
        reserveDayNumber: '',
        remark: ''
      },

      // 更新表单数据
      updateList: {
        liveId: ''
      },

      // 作废表单数据
      abrogateReserveList: {
        abrogateIdentity: ''
      },

      // 取消表单数据
      cancelReserveTableId: '',
      cancelReserveId: '',

      // 表单验证规则
      Reserves: {
        roomId: [
          { required: true, message: '请选择房间', trigger: 'change' }
        ],
        customerId: [
          { required: true, message: '请选择顾客', trigger: 'change' }
        ],
        reserveLiveTime: [
          { required: true, message: '请选择入住日期', trigger: 'change' }
        ],
        reserveDayNumber: [
          { required: true, message: '请输入入住天数', trigger: 'blur' },
          { validator: this.validateReserveDayNumber, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    /**
     * 验证入住天数是否合法
     */
    validateReserveDayNumber(rule, value, callback) {
      if (!value || isNaN(value)) {
        callback(new Error('入住天数必须为数字'))
      } else if (value < 1 || value > 366) {
        callback(new Error('入住天数必须在1到366天之间'))
      } else {
        callback()
      }
    },

    /**
     * 获取所有数据
     */
    fetchData() {
      this.selectAll()
      this.fetchRoomOptions()
      this.fetchCustomerOptions()
      this.fetchStatusOptions()
    },

    /**
     * 查询所有订房记录
     */
    selectAll() {
      selectAllReserve({
        state: this.status,
        roomNumber: this.roomNumber,
        reserveId: this.reserveId
      }).then(response => {
        console.log('订房记录数据:', response.data)
        // 过滤掉已取消的记录
        this.reserveList = response.data.filter(item => item.state !== '已取消')
      }).catch(error => {
        console.error('获取订房记录失败:', error)
      })
    },

    /**
     * 新增订房记录
     */
    addReserve(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          insertReserve({
            customerId: this.addList.customerId,
            roomId: this.addList.roomId,
            roomNumber: this.addList.roomNumber,
            customerName: this.addList.customerName,
            identificationCard: this.addList.identificationCard,
            reserveLiveTime: this.addList.reserveLiveTime,
            reserveDayNumber: this.addList.reserveDayNumber,
            remark: this.addList.remark
          }).then(response => {
            this.$message.success('新增成功！')
            this.addButtonController = false
            this.selectAll() // 刷新数据
          }).catch(error => {
            console.error('新增订房记录失败:', error)
            this.$message.error('新增失败')
          })
        } else {
          return false
        }
      })
    },

    /**
     * 更新订房状态为已入住
     */
    updateAllReserve() {
      updateReserve1({
        liveId: this.updateList.liveId,
        reserveTableId: this.updateList.reserveTableId,
      }).then(response => {
        this.$message.success('入住成功')
        this.updateButtonController = false
        this.selectAll() // 刷新数据
      }).catch(error => {
        console.error('入住操作失败:', error)
        this.$message.error('入住失败')
      })
    },

    /**
     * 取消订房
     */
    cancelAllReserve() {
      cancelReserve1({
        reserveId: this.cancelReserveId,
        reserveTableId: this.cancelReserveTableId
      }).then(response => {
        this.$message.success('取消成功')
        this.cancelReserveController = false
        this.selectAll() // 刷新数据
      }).catch(error => {
        console.error('取消操作失败:', error)
        this.$message.error('取消失败')
      })
    },

    /**
     * 作废订房
     */
    abrogateAllReserve() {
      abrogateReserve1({
        abrogateIdentity: this.abrogateReserveList.abrogateIdentity,
        reserveTableId: this.abrogateReserveList.reserveTableId
      }).then(response => {
        this.$message.success('作废成功')
        this.abrogateReserveController = false
        this.selectAll() // 刷新数据
      }).catch(error => {
        console.error('作废操作失败:', error)
        this.$message.error('作废失败')
      })
    },

    /**
     * 获取房间选项
     */
    fetchRoomOptions() {
      selectAllRoom()
        .then(response => {
          // 使用reduce去重，保留最后一个出现的房间
          const roomMap = response.data.reduce((acc, item) => {
            acc[item.roomId] = item
            return acc
          }, {})
          this.roomOptions = Object.values(roomMap)
        })
        .catch(error => {
          console.error('获取房间选项失败:', error)
          this.roomOptions = [] // 失败时清空选项
        })
    },

    /**
     * 获取顾客选项
     */
    fetchCustomerOptions() {
      selectAllCustomer()
        .then(response => {
          this.customerOptions = response.data.map(customer => ({
            customerId: customer.customerId,
            customerName: customer.customerName,
            identificationCard: customer.identificationCard
          }))
        })
        .catch(error => {
          console.error('获取顾客选项失败:', error)
        })
    },

    /**
     * 获取状态选项
     */
    fetchStatusOptions() {
      selectAllReserve()
        .then(response => {
          // 获取所有唯一状态
          const uniqueStatuses = new Set(response.data.map(item => item.state))
          this.stateOptions = [...uniqueStatuses].map(status => ({ status }))
        })
        .catch(() => {
          this.$message.error('获取状态列表失败')
        })
    },

    /**
     * 重置查询条件并重新查询
     */
    checkReserve() {
      this.state = ''
      this.roomNumber = ''
      this.reserveId = ''
      this.selectAll()
    },

    /**
     * 打开新增对话框
     */
    addButton() {
      this.addList = {
        customerId: '',
        roomId: '',
        roomNumber: '',
        customerName: '',
        reserveLiveTime: '',
        identificationCard: '',
        reserveDayNumber: '',
        remark: ''
      }
      this.addButtonController = true
    },

    /**
     * 打开入住对话框
     */
    updateButton(row) {
      this.updateList = {
        liveId: '',
        reserveTableId: row.reserveTableId,
      }
      this.updateButtonController = true
    },

    /**
     * 打开取消对话框
     */
    cancelReserveButton(row) {
      this.cancelReserveTableId = row.reserveTableId
      this.cancelReserveId = row.reserveId
      this.cancelReserveController = true
    },

    /**
     * 打开作废对话框
     */
    abrogateReserveButton(row) {
      this.abrogateReserveList = {
        abrogateIdentity: '',
        reserveTableId: row.reserveTableId
      }
      this.abrogateReserveController = true
    },

    /**
     * 关闭新增对话框
     */
    closeReserve(formName) {
      this.$refs[formName].resetFields()
      this.addButtonController = false
    },

    /**
     * 通用关闭对话框方法
     */
    closeDialog(dialogName) {
      this[dialogName] = false
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>
